<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>


<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">



  <meta name="description" content="Mysql安装和操作(flask)"/>




  <meta name="keywords" content="flask, Mysql, SQLAlchemy, 八一" />



  <meta name="baidu-site-verification" content="HhUstaSjr0" />



  <meta name="google-site-verification" content="UA-102975942-1" />






  <link rel="alternate" href="/atom.xml" title="八一">




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=2.6.0" />



<link rel="canonical" href="https://bay1.top/2017/05/19/Mysql安装和操作-flask/"/>


<link rel="stylesheet" type="text/css" href="/css/style.css?v=2.6.0" />
<link rel="stylesheet" type="text/css" href="/css/prettify.css" media="screen" />
<link rel="stylesheet" type="text/css" href="/css/sons-of-obsidian.css" media="screen" />



  <link rel="stylesheet" type="text/css" href="/lib/fancybox/jquery.fancybox.css" />




  
  <script id="baidu_analytics">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?9a885cc9fb6cd7bcef579deb8efe8a70";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <script id="google_analytics">
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-102975942-1', 'auto');
        ga('send', 'pageview');
  </script>










    <title> Mysql安装和操作(flask) - 八一 </title>
  </head>

  <body><div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/." class="logo">八一</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>

<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    
      <a href="/archives">
        <li class="mobile-menu-item">
          
          
            文章
          
        </li>
      </a>
    
      <a href="/tags">
        <li class="mobile-menu-item">
          
          
            标签
          
        </li>
      </a>
    
      <a href="/about">
        <li class="mobile-menu-item">
          
          
            关于/友链
          
        </li>
      </a>
    
      <a href="/search">
        <li class="mobile-menu-item">
          
          
            站内搜索
          
        </li>
      </a>
    
  </ul>
</nav>

    <div class="container" id="mobile-panel">
      <header id="header" class="header"><div class="logo-wrapper">
  <a href="/." class="logo">八一</a>
</div>

<nav class="site-navbar">
  
    <ul id="menu" class="menu">
      
        <li class="menu-item">
          <a class="menu-item-link" href="/archives">
            
            
              文章
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/tags">
            
            
              标签
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/about">
            
            
              关于/友链
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/search">
            
            
              站内搜索
            
          </a>
        </li>
      
    </ul>
  
</nav>

      </header>

      <main id="main" class="main">
        <div class="content-wrapper">
          <div id="content" class="content">
            
  
  <article class="post">
    <header class="post-header">
      <h1 class="post-title">
        
          Mysql安装和操作(flask)
        
      </h1>

      <div class="post-meta">
        <span class="post-time">
          2017-05-19
        </span>
        
        
        
      </div>
    </header>

    
    
  <div class="post-toc" id="post-toc">
    <h2 class="post-toc-title">文章目录</h2>
    <div class="post-toc-content">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#mysql在windows的安装"><span class="toc-text">mysql在windows的安装</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#安装的具体操作"><span class="toc-text">安装的具体操作</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#一些基本mysql操作命令"><span class="toc-text">一些基本mysql操作命令</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#mysql在flask的配置操作"><span class="toc-text">mysql在flask的配置操作</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#配置代码"><span class="toc-text">配置代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#设置模型类"><span class="toc-text">设置模型类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#数据库迁移"><span class="toc-text">数据库迁移</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#表单和mysql"><span class="toc-text">表单和mysql</span></a></li></ol></li></ol>
    </div>
  </div>


    <div class="post-content">
      
        <p>又踏上了组内任务的征程 <a id="more"></a></p>
<blockquote>
<p>这里主要记录数据库在flask中的使用，感觉数据库很重要啊！</p>
</blockquote>
<h2 id="mysql在windows的安装"><a href="#mysql在windows的安装" class="headerlink" title="mysql在windows的安装"></a>mysql在windows的安装</h2><h3 id="安装的具体操作"><a href="#安装的具体操作" class="headerlink" title="安装的具体操作"></a>安装的具体操作</h3><blockquote>
<p><span style="color: red;">以管理员身份启动CMD</span><br>进入mysql的bin文件夹，依次进行如下操作 <a href="http://pan.baidu.com/s/1dFioOQd" target="_blank" rel="noopener">mysql-5.7.18-winx64</a>,提取密码：ytue<br>第一行：初始化mysql（自动产生data文件，复制临时密码）<br>第二行：安装服务<br>第三行：和启动服务<br>第四，五行：进入mysql（用复制的临时密码进入mysql）<br>第六行：修改密码<br>第七行：查看数据库默认字符集</p>
</blockquote>
<figure class="highlight mipsasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">mysqld --initialize --user=mysql --console</span><br><span class="line">mysqld  -<span class="keyword">install</span></span><br><span class="line"><span class="keyword">net </span>start mysql</span><br><span class="line">G:\database\mysql\<span class="keyword">bin&gt;mysql </span>-u root -p</span><br><span class="line">Enter password: ************</span><br><span class="line">mysql&gt; alter user root@localhost identified <span class="keyword">by </span><span class="string">"你要修改的密码"</span><span class="comment">;</span></span><br><span class="line">mysql&gt; <span class="keyword">show </span>variables like <span class="string">'character%'</span><span class="comment">;</span></span><br></pre></td></tr></table></figure>
<h3 id="一些基本mysql操作命令"><a href="#一些基本mysql操作命令" class="headerlink" title="一些基本mysql操作命令"></a>一些基本mysql操作命令</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">show database; <span class="comment">#打印存在的数据库</span></span><br><span class="line">create database test; <span class="comment">#新建名为test的数据库</span></span><br><span class="line">show tables <span class="keyword">from</span> test;  <span class="comment">#返回test数据库下的所有表的名称</span></span><br></pre></td></tr></table></figure>
<h2 id="mysql在flask的配置操作"><a href="#mysql在flask的配置操作" class="headerlink" title="mysql在flask的配置操作"></a>mysql在flask的配置操作</h2><h3 id="配置代码"><a href="#配置代码" class="headerlink" title="配置代码"></a>配置代码</h3><blockquote>
<p>这是用的是SQLAlchemy，所需要的库需要提前配置<br>这里登陆的是root用户，要填上自己的密码，MySQL的默认端口是3306，填上之前创建的数据库名<br>第四行是设置每次请求结束后都会自动提交数据库中的变动<br>第五行进行实例化</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">app = Flask(__name__)</span><br><span class="line">app.config[<span class="string">'SECRET_KEY'</span>] =<span class="string">'hard to guess'</span></span><br><span class="line">app.config[<span class="string">'SQLALCHEMY_DATABASE_URI'</span>]=<span class="string">'mysql://root:数据库密码@localhost:3306/blog'</span> </span><br><span class="line">app.config[<span class="string">'SQLALCHEMY_COMMIT_ON_TEARDOWN'</span>]=<span class="keyword">True</span> </span><br><span class="line">db = SQLAlchemy(app)</span><br></pre></td></tr></table></figure>
<h3 id="设置模型类"><a href="#设置模型类" class="headerlink" title="设置模型类"></a>设置模型类</h3><blockquote>
<p>SQLAIchemy不但允许我们根据数据库表结构创建数据模型–models<br>它也允许我们根据数据模型创建数据库表结构</p>
</blockquote>
<p><strong>Role</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Role</span><span class="params">(db.Model)</span>:</span></span><br><span class="line">    <span class="comment"># 定义表名</span></span><br><span class="line">    __tablename__ = <span class="string">'roles'</span></span><br><span class="line">    <span class="comment"># 定义列对象</span></span><br><span class="line">    id = db.Column(db.Integer, primary_key=<span class="keyword">True</span>)</span><br><span class="line">    name = db.Column(db.String(<span class="number">64</span>), unique=<span class="keyword">True</span>)</span><br><span class="line">    user = db.relationship(<span class="string">'User'</span>, backref=<span class="string">'role'</span>)<span class="comment">#关联user模型，并在user中添加反向</span></span><br></pre></td></tr></table></figure></p>
<p><strong>User</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">User</span><span class="params">(db.Model)</span>:</span></span><br><span class="line">    __tablename__=<span class="string">"users"</span></span><br><span class="line">    id=db.Column(db.Integer,primary_key=<span class="keyword">True</span>)</span><br><span class="line">    username=db.Column(db.String(<span class="number">50</span>),unique=<span class="keyword">True</span>,index=<span class="keyword">True</span>)</span><br><span class="line">    password=db.Column(db.String(<span class="number">50</span>))</span><br><span class="line">    email=db.Column(db.String(<span class="number">100</span>)) <span class="comment">#id,username,password,email</span></span><br><span class="line">    role_id=db.Column(db.Integer,db.ForeignKey(<span class="string">"roles.id"</span>))<span class="comment">#外键指向roles表中的id列</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> flask.ext.script <span class="keyword">import</span> Manager</span><br><span class="line"><span class="keyword">from</span> flask.ext.sqlalchemy <span class="keyword">import</span> SQLAlchemy</span><br><span class="line"><span class="keyword">import</span> pymysql</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">mamager=Manager(app)</span><br><span class="line">pymysql.install_as_MySQLdb()</span><br><span class="line"></span><br><span class="line">....</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__==<span class="string">'__main__'</span>:</span><br><span class="line">	<span class="comment">#app.run(debug=True)</span></span><br><span class="line">	mamager.run()</span><br></pre></td></tr></table></figure>
<blockquote>
<p>我们可以先把这些代码写到一个文件，参考上面代码加上必要的库名和run代码，然后CMD</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">python default.py shell</span><br><span class="line"><span class="keyword">from</span> default <span class="keyword">import</span> db</span><br><span class="line">db.create_all()</span><br></pre></td></tr></table></figure>
<p><img src="https://s1.ax1x.com/2018/01/01/pSRXHx.png" alt="效果"></p>
<h3 id="数据库迁移"><a href="#数据库迁移" class="headerlink" title="数据库迁移"></a>数据库迁移</h3><blockquote>
<p>这里需要用到 <span style="color: red;">flask-migrate</span><br>然后在刚才的py文件中增加配置</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> flask.ext.migrate <span class="keyword">import</span> Migrate,MigrateCommand</span><br><span class="line">migrate=Migrate(app,db) <span class="comment">#配置迁移</span></span><br><span class="line">mamager.add_command(<span class="string">"db"</span>,MigrateCommand) <span class="comment">#配置迁移命令</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>然后CMD，利用下面的命令初始化迁移仓库,出现图片的目录就表示迁移成功了</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python default.py db init</span><br></pre></td></tr></table></figure>
<p><img src="https://s1.ax1x.com/2018/01/01/pSRvE6.png" alt="migrations"></p>
<h3 id="表单和mysql"><a href="#表单和mysql" class="headerlink" title="表单和mysql"></a>表单和mysql</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">form = LoginForm()</span><br><span class="line">    print(url_for(<span class="string">"main.index"</span>))</span><br><span class="line">    <span class="keyword">if</span> form.validate_on_submit():</span><br><span class="line">        username = form.username.data</span><br><span class="line">        password = form.password.data</span><br><span class="line">        print(User)</span><br><span class="line">        user = User.query.filter_by(username=username, password=password).first()</span><br></pre></td></tr></table></figure>
<blockquote>
<p>第七行的代码就代表在数据库中查询用户名和密码<br>在整理模块之后需要在头部导入User模型，比如下面我的代码：</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> ..models.User <span class="keyword">import</span> User</span><br></pre></td></tr></table></figure>
<p>参考链接：<a href="http://blog.csdn.net/dream_an/article/details/51058710" target="_blank" rel="noopener">数据库的安装</a><br><a href="http://blog.csdn.net/werewolf_st/article/details/45933949" target="_blank" rel="noopener">配置MySQL及其相关操作</a></p>

      
    </div>

    
      
      



      
      
    

    
      <footer class="post-footer">
        
          <div class="post-tags">
            
              <a href="/tags/flask/">flask</a>
            
              <a href="/tags/Mysql/">Mysql</a>
            
              <a href="/tags/SQLAlchemy/">SQLAlchemy</a>
            
          </div>
        
        
        
  <nav class="post-nav">
    
      <a class="prev" href="/2017/05/27/痛苦的数据结构OJ续/">
        <i class="iconfont icon-left"></i>
        <span class="prev-text nav-default">痛苦的数据结构OJ续</span>
        <span class="prev-text nav-mobile">上一篇</span>
      </a>
    
    
      <a class="next" href="/2017/05/18/nodejs反序列化漏洞/">
        <span class="next-text nav-default">nodejs反序列化漏洞</span>
        <span class="prev-text nav-mobile">下一篇</span>
        <i class="iconfont icon-right"></i>
      </a>
    
  </nav>

      </footer>
    

  </article>


          </div>
          
  <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div> 
    </div>
  </div>


        </div>
      </main>

      <footer id="footer" class="footer">

  <div class="social-links">
    
      
        
          <a href="https://github.com/bay1" class="iconfont icon-github" title="github"></a>
        
      
    
      
        
          <a href="http://weibo.com/3190704711/profile?topnav=1&wvr=6&is_all=1" class="iconfont icon-weibo" title="weibo"></a>
        
      
    
      
    
      
    
      
    
    
    
  </div>


<div class="copyright">
  <span class="copyright-year">
    
    &copy; 
     
      2016 - 
    
    2018
    <span class="author">bay1</span>
  </span>
</div>
      </footer>

      <div class="back-to-top" id="back-to-top">
        <i class="iconfont icon-up"></i>
      </div>
    </div>

    
  
  <script type="text/javascript">
    var disqus_config = function () {
        this.page.url = 'https://bay1.top/2017/05/19/Mysql安装和操作-flask/';
        this.page.identifier = '2017/05/19/Mysql安装和操作-flask/';
        this.page.title = 'Mysql安装和操作(flask)';
    };
    (function() {
    var d = document, s = d.createElement('script');

    s.src = '//https-blog-flywinky-top-1.disqus.com/embed.js';

    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
    })();  
  </script>



    
  





  
    <script type="text/javascript" src="/lib/jquery/jquery-3.1.1.min.js"></script>
  

  
    <script type="text/javascript" src="/lib/slideout/slideout.js"></script>
  

  
    <script type="text/javascript" src="/lib/fancybox/jquery.fancybox.pack.js"></script>
  


    <script type="text/javascript" src="/js/src/even.js?v=2.6.0"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=2.6.0"></script>
<script src="/js/prettify.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $('pre').addClass('prettyprint');
   prettyPrint();
 })
</script>
  </body>
</html>
